package com.meisupic.copyright.support.security;

import com.meisupic.copyright.domain.bo.SysUser;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

/**
 * creation wuxun
 *
 * @version V1.0
 * @Description: TODO
 * @date 2018/1/13 15:40
 */
@Component
public class UserIdAuthenticationProvider implements AuthenticationProvider {


  UserDetailsService userDetailsService;

  public void setUserDetailsService(
      UserDetailsService userDetailsService) {
    this.userDetailsService = userDetailsService;
  }

  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String userId = authentication.getName();
    String caid = (String) authentication.getCredentials();

    SysUser sysUser = (SysUser) userDetailsService.loadUserByUsername(userId);

    if (caid.equals(sysUser.getPassword())) {
      return new UsernamePasswordAuthenticationToken(sysUser, null, null);
    }
    throw new BadCredentialsException("用户caid错误");
  }

  @Override
  public boolean supports(Class<?> authentication) {
    return (UserIdAuthenticationToken.class
        .isAssignableFrom(authentication));
  }
}
